package com.example.java.kafka.consumer;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Properties;

public class CustomProducer {
    public static void main(String[] args) throws InterruptedException {
        KafkaProducer<String, String> kafkaProducer = CustomProducer.getCustomProducer();
        for (int i = 0; i < 5; i++) {
            String sendMessage = "ni hao, wo shi " + i;
            kafkaProducer.send(new ProducerRecord<>("consumer1", sendMessage), (metadata, exception) -> {
                if (exception == null) {
                    System.out.println(sendMessage + "已发往 => 主题：" + metadata.topic() + ", " + "分区：" + metadata.partition());
                } else {
                    exception.printStackTrace();
                }
            });
            Thread.sleep(100);
        }
        kafkaProducer.close();
        System.out.println("Producer message send end!");
    }

    private static KafkaProducer<String, String> getCustomProducer() {
        Properties properties = new Properties();
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "43.139.50.31:9092");
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        return new KafkaProducer<>(properties);
    }
}